package com.chii.color.controller;

import com.alibaba.fastjson.JSONObject;
import com.chii.color.client.ImageClient;
import com.chii.color.client.UserClient;
import com.chii.color.config.MQConfig;
import com.chii.color.po.ResponeInfo;
import com.chii.color.po.User;
import com.chii.color.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(value = "图片上传controller", tags = {"图片上传"})
@RestController
public class UploadController {

    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private UserClient userClient;
    @Resource
    private ImageClient imageClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "上传文件")
    @RequestMapping(value = "updateImage", method = RequestMethod.POST, consumes = "multipart/form-data")
    public ResponeInfo updateImage(@NotBlank(message = "username 不允许为空") @ApiParam(name = "username", value = "用户名") @RequestParam("username") String username,
                                   @ApiParam(name = "render_factor", value = "渲染因子") @RequestParam(value =
                                           "render_factor", required = false, defaultValue = "35") String renderFactor,
                                   @ApiParam(name = "file", value = "上传图片") @RequestParam("file") MultipartFile file) throws IOException {
        ResponeInfo responeInfo = new ResponeInfo();

        redisUtil.incr("MQCount", 1);


        ResponeInfo<User> userResponeInfo = userClient.getUserByUsernameFromUser(username);
        String fileName = UUID.randomUUID().toString();
        //保存图片qiniu
        String inFile = imageClient.updateImage(file, fileName + "-input.jpg", "qiniu").getData();
        //MultipartFile转file
        File temp = File.createTempFile(fileName, "-input.jpg");
        file.transferTo(temp);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", userResponeInfo.getData().getId());
        jsonObject.put("fileName", fileName);
        jsonObject.put("inFile", inFile);
        jsonObject.put("render_factor", renderFactor);
        jsonObject.put("file", temp);
        rabbitTemplate.convertAndSend(MQConfig.QUEUE, jsonObject);
        //获取队列中的消息个数
        responeInfo.setData(redisUtil.get("MQCount"));
        return responeInfo;
    }


}
